package com.ambitor.ipro.actions;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.ambitor.grass.sql.dao.SuperDao;
import com.ambitor.grass.sql.dao.impl.SuperDaoImpl;
import com.ambitor.grass.util.data.DataMap;
import com.ambitor.grass.util.data.IData;
import com.ambitor.grass.util.data.IDataset;
import com.ambitor.ipro.service.TopService;
import com.ambitor.ipro.util.Constants;
import com.ambitor.ipro.util.IDataUtils;
import com.ambitor.ipro.util.Utils;
import com.ambitor.ipro.view.Pager;
import com.taobao.api.domain.Item;

public class InstallLogAction extends JsonBaseAction {

	private static final long serialVersionUID = 1L;

	private transient SuperDao dao = null;

	public InstallLogAction() throws SQLException {
		dao = new SuperDaoImpl(pd.getConn());
	}

	@Override
	public Pager getPager() {
		return pager;
	}

	@Override
	public IDataset getDataset() {
		return dataset;
	}

	@SuppressWarnings("unchecked")
	// 根据宝贝编码列表获取宝贝相关信息
	public IDataset getItemsByIids(List<String> numIidList) throws Exception {
		TopService topService = new TopService(Constants.EVN_SWITCH,
				Constants.APP_KEY_IPROMOTION, Constants.APP_SECRET_IPROMOTION);
		List<Item> itemList = topService.getItemsWithIids(pd.getTopSessionId(),
				pd.getTopNick(), numIidList);
		IDataset itemIDataset = IDataUtils.itemsListToIDataset(itemList);
		return itemIDataset;
	}

	@SuppressWarnings("unchecked")
	// 根据宝贝编码列表获取宝贝相关信息
	public IDataset dataItems(IDataset result) throws Exception {
		List<String> installIids = new ArrayList<String>();
		for (int i = 0; i < result.size(); i++) {
			IData data = (IData) result.get(i);
			installIids.add(data.getString("IID"));
		}

		if (installIids.size() > 0) {
			IDataset itemIDataset = getItemsByIids(installIids);
			for (int i = 0; i < result.size(); i++) {
				IData data = (IData) result.get(i);
				if (data.getString("IID").equals(
						((IData) itemIDataset.get(i)).getString("iid"))) {
					data.put("IMG", ((IData) itemIDataset.get(i))
							.getString("pic_url"));
					data.put("TITLE", ((IData) itemIDataset.get(i))
							.getString("title"));
				} else {
					for (int j = 0; j < itemIDataset.count(); j++) {
						if (((IData) result.get(i)).getString("IID").equals(
								((IData) itemIDataset.get(j)).getString("iid"))) {
							data.put("IMG", ((IData) itemIDataset.get(j))
									.getString("pic_url"));
							data.put("TITLE", ((IData) itemIDataset.get(j))
									.getString("title"));
						}
					}
				}
			}
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	// 根据用户编码查询安装日志（批次）
	public String queryInstallLog() throws Exception {
		String userId = pd.getTopUserId();
		if (StringUtils.isNotBlank(userId)) {
			IData param = new DataMap();
			param.put("VUSER_ID", userId);
			IDataset result = dao.executeBaseOnSqlSql("TF_P_TRADE_PRO_BATCH",
					"SEL_BY_USERID_INSTALL", param);
			result = Utils.getIntellSettings(dao, result);

			pager.setTotalCount(result.count());
			dataset.addAll(result.subList(pager.getFirst(), pager.getEnd()));

			logger.info("共" + pager.getTotalCount() + "条记录");
			logger.info("共" + pager.getTotalPages() + "页");
			logger.info("当前请求的是第" + pager.getCurPageNo() + "页");
			logger.info("从过滤后的结果集中取出从" + (pager.getFirst() + 1) + "到"
					+ pager.getEnd() + "共" + dataset.count() + "条记录.");
		}

		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	// 根据批次查询安装日志详情
	public String queryInstallDetailLog() throws Exception {

		String batchId = pd.getRequestParameter("BATCH_ID");
		if (StringUtils.isNotBlank(batchId)) {
			IData param = new DataMap();
			param.put("VBATCH_ID", batchId);
			IDataset result = dao.executeBaseOnSqlSql("TL_P_TRADE_PRO",
					"SEL_BY_BATCHID_INSTALL", param, pager.getFirst(), pager
							.getPageSize());
			result = dataItems(result);

			pager.setTotalCount(result.count());
			dataset.addAll(result);
		}

		logger.info("共" + pager.getTotalCount() + "条记录");
		logger.info("共" + pager.getTotalPages() + "页");
		logger.info("当前请求的是第" + pager.getCurPageNo() + "页");
		logger.info("从过滤后的结果集中取出从" + (pager.getFirst() + 1) + "到"
				+ pager.getEnd() + "共" + dataset.count() + "条记录.");
		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	// 根据用户编码查询自动更新日志（批次）
	public String queryUpdateLog() throws Exception {
		String userId = pd.getTopUserId();
		if (StringUtils.isNotBlank(userId)) {
			IData param = new DataMap();
			param.put("VUSER_ID", userId);
			IDataset result = dao.executeBaseOnSqlSql("TF_P_TRADE_PRO_BATCH",
					"SEL_BY_USERID_UPDATE", param);
			result = Utils.getIntellSettings(dao, result);

			pager.setTotalCount(result.count());
			dataset.addAll(result.subList(pager.getFirst(), pager.getEnd()));
			logger.info("共" + pager.getTotalCount() + "条记录");
			logger.info("共" + pager.getTotalPages() + "页");
			logger.info("当前请求的是第" + pager.getCurPageNo() + "页");
			logger.info("从过滤后的结果集中取出从" + (pager.getFirst() + 1) + "到"
					+ pager.getEnd() + "共" + dataset.count() + "条记录.");

		}

		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	// 根据批次查询自动更换日志详情
	public String queryUpdateDetailLog() throws Exception {
		String batchId = pd.getRequestParameter("BATCH_ID");
		if (StringUtils.isNotBlank(batchId)) {
			IData param = new DataMap();
			param.put("VBATCH_ID", batchId);
			IDataset result = dao.executeBaseOnSqlSql("TL_P_TRADE_PRO",
					"SEL_BY_BATCHID_UPDATE", param, pager.getFirst(), pager
							.getPageSize());
			result = dataItems(result);
			pager.setTotalCount(result.count());
			dataset.addAll(result);
			logger.info("共" + pager.getTotalCount() + "条记录");
			logger.info("共" + pager.getTotalPages() + "页");
			logger.info("当前请求的是第" + pager.getCurPageNo() + "页");
			logger.info("从过滤后的结果集中取出从" + (pager.getFirst() + 1) + "到"
					+ pager.getEnd() + "共" + dataset.count() + "条记录.");
		}

		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	// 根据用户编码查询卸载日志（批次）
	public String queryUninstallLog() throws Exception {
		String userId = pd.getTopUserId();
		if (StringUtils.isNotBlank(userId)) {
			IData param = new DataMap();
			param.put("VUSER_ID", userId);
			IDataset result = dao.executeBaseOnSqlSql("TF_P_TRADE_PRO_BATCH",
					"SEL_BY_USERID_UNINSTALL", param);
			for (int i = 0; i < result.size(); i++) {
				if ("BATCH".equals((result.getData(i))
						.getString("UNINSTALL_SETTING"))) {
					param = new DataMap();
					param.put("VUSER_ID", userId);
					param.put("VPRO_ID", ((IData) result.get(i))
							.getString("PRO_ID"));
					IDataset resultUserProBatch = dao.executeBaseOnSqlSql(
							"TF_P_USER_PRO_BATCH", "SEL_USERPRO_BY_USERID",
							param);
					if (resultUserProBatch.size() > 0)
						result.getData(i).putAll(resultUserProBatch.getData(0));
				}
			}

			result = Utils.getIntellSettings(dao, result);

			pager.setTotalCount(result.count());
			dataset.addAll(result.subList(pager.getFirst(), pager.getEnd()));

			logger.info("共" + pager.getTotalCount() + "条记录");
			logger.info("共" + pager.getTotalPages() + "页");
			logger.info("当前请求的是第" + pager.getCurPageNo() + "页");
			logger.info("从过滤后的结果集中取出从" + (pager.getFirst() + 1) + "到"
					+ pager.getEnd() + "共" + dataset.count() + "条记录.");
		}
		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	// 根据批次查询卸载日志详情
	public String queryUninstallDetailLog() throws Exception {

		String batchId = pd.getRequestParameter("BATCH_ID");
		IData param = new DataMap();
		if (StringUtils.isNotBlank(batchId)) {
			param.put("VBATCH_ID", batchId);
			IDataset result = dao.executeBaseOnSqlSql("TL_P_TRADE_PRO",
					"SEL_BY_BATCHID_UNINSTALL", param, pager.getFirst(), pager
							.getPageSize());
			result = dataItems(result);

			pager.setTotalCount(result.count());
			dataset.addAll(result);
		}

		logger.info("共" + pager.getTotalCount() + "条记录");
		logger.info("共" + pager.getTotalPages() + "页");
		logger.info("当前请求的是第" + pager.getCurPageNo() + "页");
		logger.info("从过滤后的结果集中取出从" + (pager.getFirst() + 1) + "到"
				+ pager.getEnd() + "共" + dataset.count() + "条记录.");
		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	// 根据用户编码查询正在使用推广的主宝贝
	public String queryUsingLog() throws Exception {
		String userId = pd.getTopUserId();
		if (StringUtils.isNotBlank(userId)) {
			IData param = new DataMap();
			param.put("VUSER_ID", userId);
			IDataset result = dao.executeBaseOnSqlSql("TF_P_USER_PRO_BATCH",
					"SEL_BY_USERID_FLAG", param, pager.getFirst(), pager
							.getPageSize());
			result = Utils.getIntellSettings(dao, result);
			result = dataItems(result);

			pager.setTotalCount(result.count());
			dataset.addAll(result);
		}

		logger.info("共" + pager.getTotalCount() + "条记录");
		logger.info("共" + pager.getTotalPages() + "页");
		logger.info("当前请求的是第" + pager.getCurPageNo() + "页");
		logger.info("从过滤后的结果集中取出从" + (pager.getFirst() + 1) + "到"
				+ pager.getEnd() + "共" + dataset.count() + "条记录.");
		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	public void reExecute() throws Exception {
		String batchId = pd.getRequestParameter("BATCH_ID");
		IData param = new DataMap();
		param.put("VBATCH_ID", batchId);
		dao.executeBaseOnSqlSql("TF_P_TRADE_PRO_BATCH", "UPDATE_BY_BATCHID",
				param);
	}

}
